package com.app.modules.code.controller;

import java.io.*;
import java.sql.Connection;
import com.alibaba.druid.pool.DruidDataSource;
import com.app.common.utils.*;
import com.app.common.vo.AjaxResultData;
import com.app.config.datasource.DynamicDataSourceUtil;
import com.app.modules.code.domain.Sysdbconfig;
import com.app.modules.code.mapper.SysdbconfigMapper;
import com.app.modules.code.service.SysdbconfigService;
import com.app.modules.code.vo.CodeconfigVo;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author MyBatisPlus
 * @since 2023-07-19
 */
@Api(value = "数据源管理控制器", tags = {"数据源管理接口"})
@RestController
@RequestMapping("/sysdbconfig")
public class SysdbconfigController {


    @Autowired
    private SysdbconfigService sysdbconfigService;


    @ApiOperation(httpMethod="GET",value="获取全部数据源配置",notes="")
    @GetMapping("/allDBlist")
    public AjaxResultData allDBlist() {
        List<Sysdbconfig>  dblist = sysdbconfigService.list();
        return AjaxResultData.succ("查询成功",dblist);
    }


    @ApiOperation(httpMethod = "POST", value = "数据源配置分页列表", notes = "需要传入参数 \n" +
            "{\n" +
            " \"currentPage\": 1,  #第几页 \n" +
            " \"size\": 10,        #每页数量 \n" +
            " \"condition\": \"xxxx\",   #查询条件 \n" +
            "}")
    @PostMapping("/pageList")
    public AjaxResultData pageList(@RequestBody Map<String, Object> params) {
        Integer currentPage = (Integer) params.get("currentPage");
        Integer size = (Integer) params.get("size");
        String condition = (String) params.get("condition");
        PageHelper.startPage(currentPage,size);
        List<Sysdbconfig> dbpage = sysdbconfigService.selectSysdbconfigPage(condition);
        return AjaxResultData.succ("查询成功",dbpage);
    }


    @ApiOperation(httpMethod="POST",value="代码生成工具并打包下载",notes="")
    @RequestMapping(path = "/genCodeszip",method={RequestMethod.POST,RequestMethod.GET})
    public void genCodeszip(@RequestBody CodeconfigVo codevo, HttpServletResponse response) throws IOException {
        //判断数据源是否存在
        Sysdbconfig db =  sysdbconfigService.getById(codevo.getDbid());
        if(db != null) {
            String  sourceFilePath = MyBatisPlusGeneratorUtils.generatorCode(codevo,db);
            String zipFileName = "code";
            FileUtil.httpDownloadZipFile(sourceFilePath,response, zipFileName);
        }

    }
    
    /**
     * 测试连接数据源
     * */
    @ApiOperation(httpMethod = "POST", value = "测试连接数据源", notes = "需要传入参数 \n" +
            "{\n" +
            " \"dbid\": 1,  #数据源id \n" +
            "}")
    @PostMapping("/connect")
    public AjaxResultData connect(@RequestBody Map<String, Object> params) {

        Integer dbid = (Integer)params.get("dbid");
        Sysdbconfig sysdb = sysdbconfigService.getById(dbid);
        if(sysdb == null) {
            return AjaxResultData.err("dbid="+dbid+"不存在");
        }
        Connection connection = null;
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUsername(sysdb.getUsername());
        druidDataSource.setPassword(sysdb.getPassword());
        druidDataSource.setUrl(sysdb.getUrl());

        try {
            druidDataSource.setBreakAfterAcquireFailure(true);
            druidDataSource.setConnectionErrorRetryAttempts(0);
            connection = druidDataSource.getConnection(5000);
            if(connection != null) {
                connection.close();
                return AjaxResultData.succ("连接成功!");
            }
            return AjaxResultData.err("连接失败!");
        } catch (Exception e) {
            return AjaxResultData.err("连接失败!");
        }

    }



    @ApiOperation(value = "添加数据源配置", notes = "")
    @PostMapping("/add")
    public AjaxResultData add(Sysdbconfig sysdbconfig) {
        sysdbconfig.setStatus("1");
        sysdbconfig.setCreatetime(DateUtil.getTime());
        sysdbconfig.setUpdatetime(DateUtil.getTime());
        boolean flag = sysdbconfigService.save(sysdbconfig);
        DruidDataSource dds = DataSourceComposeUtils.composeDruidDataSource(sysdbconfig);
        //添加数据源
        DynamicDataSourceUtil.addTargetDataSource(sysdbconfig.getDbname()+"-"+ sysdbconfig.getId(),dds);
        //刷新数据源
        DynamicDataSourceUtil.flushDataSource();
        return  AjaxResultData.succ("添加成功",flag);
    }

    @ApiOperation(value = "编辑数据源配置", notes = "")
    @PostMapping("/edit")
    public AjaxResultData edit(Sysdbconfig sysdbconfig) {
        sysdbconfig.setStatus("1");
        sysdbconfig.setUpdatetime(DateUtil.getTime());
        Sysdbconfig sysdb= sysdbconfigService.getById(sysdbconfig.getId());
        if(sysdb == null) {
            return  AjaxResultData.succ("修改失败");
        }
        boolean flag = sysdbconfigService.updateById(sysdbconfig);
        DruidDataSource dds = DataSourceComposeUtils.composeDruidDataSource(sysdbconfig);
        //更新数据源
        DynamicDataSourceUtil.replaceTargetDataSource(sysdbconfig.getDbname()+"-"+ sysdbconfig.getId(),dds);
        DynamicDataSourceUtil.flushDataSource();
        return  AjaxResultData.succ("修改成功",flag);
    }

    @ApiOperation(httpMethod = "POST", value = "删除数据源配置", notes = "需要传入参数 \n" +
            "{\n" +
            " \"dbid\": 1,  #数据源id \n" +
            "}")
    @PostMapping("/del")
    public AjaxResultData del(@RequestBody Map<String, Object> params) {

        Integer dbid = (Integer)params.get("dbid");
        Sysdbconfig sysdb = sysdbconfigService.getSysdbconfigByid(dbid);
        if(sysdb != null) {
           //删除数据源
           DynamicDataSourceUtil.deleteTargetDataSource(sysdb.getDbname()+"-"+ sysdb.getId());
           sysdbconfigService.removeById(sysdb.getId());
           return  AjaxResultData.succ("删除成功");
        }
        return  AjaxResultData.succ("删除失败");
    }




































}

